<?php
define('SCR', 'index');
require_once ('global.php');
//20130929 caoyj add start
L::loadClass('forum', 'forum', false);
//20130929 caoyj add end
$cateid = (int) S::getGP('cateid');
$m = S::getGP('m');
if ($db_channeldomain && $secdomain = array_search($pwServer['HTTP_HOST'], $db_channeldomain)) {
	$m = 'area';
	$alias = $secdomain;
	define('HTML_CHANNEL', 1);
}
//20160122 caoyj add start
if(strpos($_SERVER['HTTP_REFERER'],'m.jx09.com')){
	$_SERVER['HTTP_USER_AGENT'] = 'PC';
}
if (is_mobile() && $_SERVER['HTTP_HOST'] == 'www.jx09.com' && !strpos($_SERVER['REQUEST_URI'],'gemdiary')) {
	//header('Location:http://m.jx09.com');
    //header('Location:http://quan.jx09.com');
}
//20160122 caoyj add end
selectMode($m);
if (defined('M_P') && file_exists(M_P . 'index.php')) {
	pwCache::getData(S::escapePath(D_P . 'data/bbscache/' . $db_mode . '_config.php'));
	if (file_exists(M_P . 'require/core.php')) {
		require_once (M_P . 'require/core.php');
	}
	$basename = "index.php?m=$m";
	require_once (M_P . 'index.php');
	exit();
}

pwCache::getData(D_P . 'data/bbscache/cache_index.php');
pwCache::getData(D_P . 'data/bbscache/forum_cache.php');
//20130929 caoyj add start
 $pwforum = new PwForum($fid);

 $isGM = $isBM = $admincheck = $managecheck = $pwPostHide = $pwSellHide = $pwEncodeHide = 0;
 $pwSystem = array();
 if ($groupid != 'guest') {
 	//$isGM = S::inArray($windid,$manager);
 	$isGM = $groupid==3;
 	$isBM = $pwforum->isBM($windid);
 	$admincheck = ($isGM || $isBM) ? 1 : 0;
 	if (!$isGM) {#非创始人权限获取
 		$pwSystem = pwRights($isBM);
 		if ($pwSystem && ($pwSystem['tpccheck'] || $pwSystem['digestadmin'] || $pwSystem['lockadmin'] || $pwSystem['pushadmin'] || $pwSystem['coloradmin'] || $pwSystem['downadmin'] || $pwSystem['delatc'] || $pwSystem['moveatc'] || $pwSystem['copyatc'] || $pwSystem['topped'] || $pwSystem['unite'] || $pwSystem['pingcp'] || $pwSystem['areapush'] || $pwSystem['split'])) {
 			$managecheck = 1;
 		}
 		$pwPostHide = $pwSystem['posthide'];
 		$pwSellHide = $pwSystem['sellhide'];
 		$pwEncodeHide = $pwSystem['encodehide'];
 	} else {
 		$managecheck = $pwPostHide = $pwSellHide = $pwEncodeHide = 1;
 	}
 }
//20130929 caoyj add end
//notice
$noticedb = array();
foreach ($notice_A as $value) {
	if ($value['startdate'] <= $timestamp && (!$value['enddate'] || $value['enddate'] >= $timestamp)) {
		$value['startdate'] = $value['stime'] ? $value['stime'] : get_date($value['startdate'], 'y-m-d');
		!$value['url'] && $value['url'] = 'notice.php#' . $value['aid'];
		$noticedb[$value['aid']] = $value;
	}
}
$notice_A = $noticedb;
unset($noticedb);
$topics = $article = $tposts = 0;

//SEO Settings
bbsSeoSettings('index');

$newpic = (int) GetCookie('newpic');
$forumdb = $catedb = $showsub = array();
$c_htm = 0;
$sqlwhere = '';
$updateDaily = 1;

if ($cateid > 0) {
	$catestyle = $forum[$cateid]['style'];
	($catestyle && file_exists(D_P . "data/style/$catestyle.php")) && $skin = $catestyle;
	$_seo = array('title' => $forum[$cateid]['title'], 'metaDescription' => $forum[$cateid]['metadescrip'], 'metaKeywords' => $forum[$cateid]['keywords']);
	bbsSeoSettings('thread', $_seo, $forum[$cateid]['name'], '');
	$sqlwhere = 'AND (f.fid=' . S::sqlEscape($cateid) . ' OR f.fup=' . S::sqlEscape($cateid) . ')';
	$updateDaily = 0;
} elseif ($db_forumdir) {
	require_once (R_P . 'require/dirname.php');
}
require_once (R_P . 'require/header.php');
!$db_showcms && $sqlwhere .= " AND f.cms!='1'";

/*The app client*/
if ($db_siteappkey && ($db_apps_list['17']['status'] == 1 || is_array($db_threadconfig))) {
	$appclient = L::loadClass('appclient');
	if (is_array($db_threadconfig)) {
		$threadright = (array) $appclient->getThreadRight();
	}
}
/*The app client*/

if ($cookie_deploy = $_COOKIE['deploy']) {
	$deployfids = array_flip((array)explode("\t", $cookie_deploy));
	unset($cookie_deploy);
} else {
	$deployfids = array();
}

if (!$cateid && Perf::checkMemcache()) {
	$_cacheService = Perf::getCacheService();
	$_tmpForums = $_cacheService->get('all_forums_info');
}

if (!Perf::checkMemcache() || !$_tmpForums){
	$query = $db->query("SELECT f.fid,f.name,f.type,f.childid,f.fup,f.logo,f.descrip,f.metadescrip,f.forumadmin,f.across,f.allowhtm,f.password,f.allowvisit,f.showsub,f.ifcms,fd.tpost,fd.topic,fd.article,fd.subtopic,fd.top1,fd.lastpost FROM pw_forums f LEFT JOIN pw_forumdata fd USING(fid) WHERE f.ifsub='0' AND f.ifcms!=2 $sqlwhere ORDER BY f.vieworder");
	$_tmpForums = array();
	while ($forums = $db->fetch_array($query)) {
		$_tmpForums[$forums['fid']] = $forums;
	}
	!$cateid && Perf::checkMemcache() &&  $_cacheService->set('all_forums_info', $_tmpForums, 300);
}
//24小时帖数统计start
$sqlcount = "
SELECT
	fid
,   SUM(num) AS tpost
FROM
(		SELECT
			fid
		,	COUNT(*) AS num
		FROM
		(
			SELECT *
			FROM
				pw_posts
			WHERE
				postdate BETWEEN UNIX_TIMESTAMP() -24 *60 *60 AND UNIX_TIMESTAMP()
		) as temp
		WHERE
			temp.fid IN (SELECT f.fid FROM pw_forums f LEFT JOIN pw_forumdata fd USING(fid) WHERE f.ifsub='0' AND f.ifcms!=2 )
		GROUP BY
			temp.fid
UNION ALL
		SELECT
			fid
		,	count(*) as num
		FROM
		(
			SELECT *
			FROM
				pw_posts1
			WHERE
				postdate BETWEEN UNIX_TIMESTAMP() -24 *60 *60 AND UNIX_TIMESTAMP()
		) AS temp
		WHERE
			temp.fid IN (SELECT f.fid FROM pw_forums f LEFT JOIN pw_forumdata fd USING(fid) WHERE f.ifsub='0' AND f.ifcms!=2 )
		GROUP BY
			temp.fid		
UNION ALL
		SELECT
			fid
		,	count(*) as num
		FROM
		(
			SELECT *
			FROM
				pw_threads
			WHERE
				postdate BETWEEN UNIX_TIMESTAMP() -24 *60 *60 AND UNIX_TIMESTAMP()
		) AS temp
		WHERE
			temp.fid IN (SELECT f.fid FROM pw_forums f LEFT JOIN pw_forumdata fd USING(fid) WHERE f.ifsub='0' AND f.ifcms!=2 )
		GROUP BY
			temp.fid) AS result
GROUP BY fid";

$sqlquery = $db->query($sqlcount);

$sqlTop10 = "	SELECT 
					subject
				,	tid
				FROM
					pw_threads
				WHERE
					fid <> '0'
				ORDER BY 
					postdate 
				DESC LIMIT 11";


$sqlmain =	"
		select temp.tid,temp.fid,temp.subject,pf.name from
(
SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 196
			ORDER BY postdate DESC
			LIMIT 0,3) b
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 202
			ORDER BY postdate DESC
			LIMIT 0,3) c
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 304
			ORDER BY postdate DESC
			LIMIT 0,3) d
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 216
			ORDER BY postdate DESC
			LIMIT 0,3) e
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 299
			ORDER BY postdate DESC
			LIMIT 0,3) f
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 197
			ORDER BY postdate DESC
			LIMIT 0,3) g
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 262
			ORDER BY postdate DESC
			LIMIT 0,3) h
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 320
			ORDER BY postdate DESC
			LIMIT 0,3) i
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 223
			ORDER BY postdate DESC
			LIMIT 0,3) j
			UNION
			SELECT * FROM
			(
			SELECT tid,fid,subject
			FROM pw_threads
			WHERE fid = 831
			ORDER BY postdate DESC
			LIMIT 0,3) a
			
) as temp
left join pw_forums as pf
on
temp.fid = pf.fid";

$sqlTop8member = "  SELECT 
							icon,
							username,
							uid 
					 FROM 
							pw_members AS pm 
					 where 
						
							pm.username IN ('新闻鼻祖','cwy8d6','l2mgac','南屏晚钟','t86yp72','手机hdm','百工技艺陈老师','风吹杨柳') ";

$sqlqueryTop10 = $db->query($sqlTop10);

while ($rtTop10s = $db->fetch_array($sqlqueryTop10)) {
	$tempTop10['subject'] = $rtTop10s['subject'];
	$tempTop10['tid'] = $rtTop10s['tid'];
	
	$tempTop[] = $tempTop10;
}

$sqlquerymain = $db->query($sqlmain);

while ($rtmains = $db->fetch_array($sqlquerymain)) {
	if(strlen($rtmains['subject']) >= 40){
		$tempmain['subject'] = substrs($rtmains['subject'],40).".";
	}else{
		$tempmain['subject'] = $rtmains['subject'];
	}
	$tempmain['tid'] = $rtmains['tid'];
	$tempmain['fid'] = $rtmains['fid'];
	$tempmain['name'] = $rtmains['name'];
	$tempmains[] = $tempmain;
}
require_once (R_P . 'require/showimg.php');
$sqlqueryTop8member = $db->query($sqlTop8member);
while ($rtTop8member = $db->fetch_array($sqlqueryTop8member)) {
	$temp['icon'] = showfacedesign($rtTop8member['icon'], 1, 's');
	$tempTop8member['icon'] = $temp['icon'][0];
	//if(!$rtTop8member['icon']){
	//	$tempTop8member['icon'] = 'none.gif';
	//}else{
	//	$tempTop8member['icon'] =  substr($rtTop8member['icon'],0,strpos($rtTop8member['icon'],'|'));
	//	}
	$tempTop8member['username'] = $rtTop8member['username'];
	$tempTop8member['uid'] = $rtTop8member['uid'];
	$tempTop8members[] = $tempTop8member;

}
//20130929 caoyj add end
$fidarray = array();

while ($rt = $db->fetch_array($sqlquery)) {
	$fidarray[$rt['fid']] = $rt['tpost'];
}
//24小时帖数统计end

foreach ($_tmpForums as $forums) {
	if ($forums['type'] === 'forum') {
		if ($forums['showsub'] && $forums['childid']) {
			$showsub[$forums['fid']] = '';
		}
		
		$forums['topics'] = $forums['topic'] + $forums['subtopic'];
		$article += $forums['article'];
		$topics += $forums['topics'];
		$tposts += $forums['tpost'];
		//24小时帖数统计start
		$forums['tpostNew'] = '0';
		if(array_key_exists($forums['fid'],$fidarray)){
			$forums['tpostNew'] = ceil($fidarray[$forums['fid']]*1.5);
		}
		//24小时帖数统计end
		$forums['au'] = $forums['admin'] = '';
		if (S::inArray($windid, $manager) || (!$forums['password'] && (!$forums['allowvisit'] || allowcheck($forums['allowvisit'], $groupid, $winddb['groups'], $forums['fid'], $winddb['visit'])))) {
			list($forums['t'], $forums['au'], $forums['newtitle'], $forums['ft']) = explode("\t", $forums['lastpost']);
			$forums['pic']      = $newpic < $forums['newtitle'] && ($forums['newtitle'] + $db_newtime > $timestamp) ? 'new' : 'old';
			$forums['newtitle'] = get_date($forums['newtitle']);
			$forums['t']        = substrs($forums['t'], 26);
		} elseif ($forum[$forums['fid']]['f_type'] === 'hidden') {
			if ($forums['password'] && allowcheck($forums['allowvisit'], $groupid, $winddb['groups'], $forums['fid'], $winddb['visit'])) {
				$forums['pic'] = 'lock';
			} else {
				if (!S::inArray($windid, $manager)) {
					continue;
				}
			}
		} else {
			$forums['pic'] = 'lock';
		}
		$forums['allowhtm'] == 1 && $c_htm = 1;
		if ($db_indexfmlogo == 2) {
			if (!empty($forums['logo']) && strpos($forums['logo'], 'http://') !== false) {
				$forums['logo'] = $forums[logo];
			} elseif (!empty($forums['logo'])) {
				$forumLogo = geturl($forums[logo]);
				$forums['logo'] = $forumLogo[0];
			}
		} elseif ($db_indexfmlogo == 1 && file_exists("$imgdir/$stylepath/forumlogo/$forums[fid].gif")) {
			$forums['logo'] = "$imgpath/$stylepath/forumlogo/$forums[fid].gif";
		} else {
			$forums['logo'] = '';
		}
		if ($forums['forumadmin']) {
			$forumadmin = explode(',', $forums['forumadmin']);
			foreach ($forumadmin as $value) {
				if ($value) {
					if (!$db_adminshow) {
						$forums['admin'] .= '<a href="u.php?username=' . rawurlencode($value) . '" class=" _cardshow" target="_blank" data-card-url="pw_ajax.php?action=smallcard&type=showcard&username='.rawurlencode($value).'" data-card-key='.$value.'>'.$value.'</a> ';
					} else {
						$forums['admin'] .= "<option value=\"$value\">$value</option>";
					}
				}
			}
		}
		
		/*The app client*/
		if ($db_siteappkey && $db_apps_list['17']['status'] == 1) {
			$forums['forumappinfo'] = $appclient->showForumappinfo($forums['fid'], 'forum_erect,forum_across', '17');
		}
		/*The app client*/
		
		$forumdb[$forums['fup']][] = $forums;
	} elseif ($forums['type'] === 'category') {
		if (isset($deployfids[$forums['fid']])) {
			$forums['deploy_img'] = 'open';
			$forums['tbody_style'] = 'none';
			$forums['admin'] = '';
		} else {
			$forums['deploy_img'] = 'fold';
			$forums['tbody_style'] = $forums['admin'] = '';
		}
		if ($forums['forumadmin']) {
			$forumadmin = explode(',', $forums['forumadmin']);
			foreach ($forumadmin as $key => $value) {
				if ($value) {
					if ($key == 10) {
						$forums['admin'] .= '...';
						break;
					}
					$forums['admin'] .= '<a href="u.php?username=' . rawurlencode($value) . '" class="cfont _cardshow" target="_blank" data-card-url="pw_ajax.php?action=smallcard&type=showcard&username='.rawurlencode($value).'" data-card-key='.$value.'>' . $value . '</a> ';
				}
			}
		}
		$catedb[] = $forums;
	}
} 
$db->free_result($query);
// View sub
if (!empty($showsub)) {
	foreach ($forum as $value) {
		if (isset($showsub[$value['fup']]) && $value['f_type'] != 'hidden' && $value['ifcms'] != 2) {
			$showsub[$value['fup']] .= ($showsub[$value['fup']] ? ' | ' : '') . "<a href=\"thread.php?fid=$value[fid]\">$value[name]</a>";
		}
	}
}
unset($forums, $forum, $db_showcms);
//info deploy
if (isset($deployfids['info'])) {
	$cate_img = 'open';
	$cate_info = 'none';
} else {
	$cate_img = 'fold';
	$cate_info = '';
}
// update birth day
if ($db_indexshowbirth) {
	$brithcache = '';
	require_once (R_P . 'require/birth.php');
}
// get bbsinfo
if(Perf::checkMemcache()){
	$_cacheService = Perf::getCacheService();
	$_bbsInfoResult = $_cacheService->get('bbsinfo_id_1');
	if(!$_bbsInfoResult){
		$_bbsInfoService = L::loadClass('BbsInfoService', 'forum'); 
		$_bbsInfoResult = $_bbsInfoService->getBbsInfoById(1);
	}
	extract($_bbsInfoResult);
}else{
	extract($db->get_one("SELECT * FROM pw_bbsinfo WHERE id=1"));
}
$newmember = '<a href="u.php?username=' . rawurlencode($newmember) . '" target="_blank" class=" _cardshow" data-card-url="pw_ajax.php?action=smallcard&type=showcard&username='.rawurlencode($newmember).'" data-card-key='.$newmember.'>' . $newmember . '</a>';

$article += $o_post;
$topics  += $o_post;
$tposts  += $o_tpost;

// online users
Update_ol();
if (empty($db_online)) {
	include_once (D_P . 'data/bbscache/olcache.php');
} else {
	$userinbbs = $guestinbbs = 0;	
	if (count($online_info =  explode("\t", GetCookie('online_info'))) == 3 && $timestamp - $online_info[0] < 60){
		list(, $userinbbs, $guestinbbs) = $online_info;
	}else {
		$onlineService = L::loadClass('OnlineService', 'user');
		$userinbbs = $onlineService->countOnlineUser();
		$guestinbbs = $onlineService->countOnlineGuest();
		Cookie('online_info', $timestamp . "\t" . $userinbbs . "\t" . $guestinbbs);
	}
}

if ($last_statistictime == 0 || get_date($timestamp,'G') - get_date($last_statistictime,'G') > 1 ||  $timestamp - $last_statistictime > 3600) {
	$stasticsService = L::loadClass('Statistics', 'datanalyse');
	$stasticsService->updateOnlineInfo();
}

$usertotal = $guestinbbs + $userinbbs;
if ($db_indexonline) {
	S::gp(array('online'));
	empty($online) && $online = GetCookie('online');
	if ($online == 'yes') {
		if ($usertotal > 2000 && !S::inArray($windid, $manager)) {
			//$online = 'no';
			Cookie('online', 'no');
		} else {
			$index_whosonline = '';
			$db_online = intval($db_online);
			Cookie('online', $online);
			include_once S::escapePath(R_P . "require/online_{$db_online}.php");
		}
	}
	if ($online == 'no') Cookie('online', 'no');
}
$showgroup = $db_showgroup ? explode(',', $db_showgroup) : array();
// Share union
if ($db_indexmqshare && $sharelink[1]) {
	$sharelink[1] = "<marquee scrolldelay=\"100\" scrollamount=\"4\" onmouseout=\"if (document.all!=null){this.start()}\" onmouseover=\"if (document.all!=null){this.stop()}\" behavior=\"alternate\">$sharelink[1]</marquee>";
}

if ($db_hostweb == 1 && $updateDaily && $tdtcontrol < $tdtime && !defined('M_P')) {
	require_once (R_P . 'require/updateforum.php');
	updateshortcut();
	pwQuery::update('pw_bbsinfo', 'id=:id', array(1), array('yposts' => $tposts, 'tdtcontrol' => $tdtime, 'o_tpost' => 0));
	pwQuery::update('pw_forumdata', 'tpost<>:tpost', array(0), array('tpost'=>0));
	pwQuery::update('pw_forumdata', 'tpost_t<>:tpost', array(0), array('tpost_t'=>0));
}

// update posts hits
if ($c_htm || $db_hits_store == 2) {
	$db_hithour == 0 && $db_hithour = 4;
	$hit_wtime = $hit_control * $db_hithour;
	$hit_wtime > 24 && $hit_wtime = 0;
	$hitsize = @filesize(D_P . 'data/bbscache/hits.txt');
	if ($hitsize && ($hitsize > 1024 || ($timestamp - $hit_tdtime) > $hit_wtime * 3600) && procLock('hitupdate')) {
		require_once (R_P . 'require/hitupdate.php');
		procUnLock('hitupdate');
	}
}

if ($higholnum < $usertotal) {
	pwQuery::update('pw_bbsinfo', 'id=:id', array(1), array('higholnum' => $usertotal, 'higholtime' => $timestamp));
	$higholnum = $usertotal;
}
if ($hposts < $tposts) {
	pwQuery::update('pw_bbsinfo', 'id=:id', array(1), array('hposts'=>$tposts));
	$hposts = $tposts;
}
$tposts = ceil($tposts*2.5);
//20130827 caoyj add start
$totalmember = $totalmember + 220000;
//20130827 caoyj add end
$mostinbbstime = get_date($higholtime);
if (!$ol_offset && $db_onlinelmt != 0 && $usertotal >= $db_onlinelmt) {
	Cookie('ol_offset', '', 0);
	Showmsg('most_online');
}
if ($plantime && $timestamp > $plantime && procLock('task')) {
	require_once (R_P . 'require/task.php');
	procUnLock('task');
}
//20160122 caoyj add start
if(strpos($_SERVER['HTTP_REFERER'],'m.jx09.com')){
	$_SERVER['HTTP_USER_AGENT'] = 'PC';
}
if (is_mobile()) {
	header('Location:http://m.jx09.com');
}

require_once PrintEot('index');
CloudWind::yunSetCookie(SCR);
footer();
function is_mobile() { 
    $user_agent = $_SERVER['HTTP_USER_AGENT']; 
    $mobile_agents = array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi", 
    "android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio", 
    "au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu", 
    "cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ", 
    "fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi", 
    "htc","huawei","hutchison","inno","ipad","ipaq","iphone","ipod","jbrowser","kddi", 
    "kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo", 
    "mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-", 
    "moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia", 
    "nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-", 
    "playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo", 
    "samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank", 
    "sony","spice","sprint","spv","symbian","talkabout","tcl-","teleca","telit", 
    "tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin", 
    "vk-","voda","voxtel","vx","wap","wellco","wig browser","wii", 
    "wireless","xda","xde","zte"); 
    $is_mobile = false; 
    foreach ($mobile_agents as $device) { 
        if (stristr($user_agent, $device)) { 
            $is_mobile = true; 
            break; 
        } 
    } 
    return $is_mobile; 
}
?>